#!/bin/sh
# PCP QA Test No. 510
# pmlogger -Dlog calls __pmDumpResult() which fails for usage with
# pmlc control requests
#
# Copyright (c) 2012 Ken McDonell.  All Rights Reserved.
#
# check-group-include: pmlogger

seq=`basename $0`
echo "QA output created by $seq"

# get standard environment, filters and checks
. ./common.product
. ./common.filter
. ./common.check

_check_job_scheduler

status=1
trap "_cleanup" 0 1 2 3 15
needclean=true

_check_pmlogger_lock()
{
    rm -f $tmp.checklog
    find $PCP_ARCHIVE_DIR -name lock \
    | while read _lock
    do
	ls -l $_lock >>$seq_full
	# lock file could have vanished by now ...
	#
	cat $_lock >>$tmp.checklock 2>/dev/null
    done
    if [ -s $tmp.checklock ]
    then
	echo "!!! found pmlogger lock(s) @ `date` ..." >>$seq_full
	cat $tmp.checklock >>$seq_full
	echo "I am PID $$" >>$seq_full
	cat $tmp.checklock \
	| while read _pid _who
	do
	    echo "locker pid $_pid who $_who" >>$seq_full
	    _pstree_all $_pid >>$seq_full
	done
    else
	echo "!!! no pmlogger locks @ `date` ..." >>$seq_full
    fi
}

_cleanup()
{
    if $needclean
    then
	_restore_config $control
	needclean=false
	_restore_primary_logger
	echo "Stop/start at end ... " `date` >>$seq_full
	_check_pmlogger_lock
	_service pmlogger start 2>&1 | _filter_pcp_start
	_wait_for_pmlogger
	_restore_job_scheduler $tmp.cron $tmp.systemd $sudo
	echo "Stop/start done " `date` >>$seq_full
	_check_pmlogger_lock
    fi
    $sudo rm -f $tmp.*
    exit $status
}

_filter()
{
    sed \
	-e 's/Version [0-9].*/Version VERSION/'
}

control=$PCP_PMLOGGERCONTROL_PATH
[ -f $PCP_PMLOGGERCONTROL_PATH.d/local ] && \
control=$PCP_PMLOGGERCONTROL_PATH.d/local

# stop primary logger, add -Dlog to config file and restart pmlogger
echo "Stop/start at beginning ... " `date` >>$seq_full
_check_pmlogger_lock
_remove_job_scheduler $tmp.cron $tmp.systemd $sudo
_check_pmlogger_lock
if ! _service pmlogger stop >>$seq_full 2>&1; then _exit 1; fi
echo "Stop/start done " `date` >>$seq_full

sed -e '/^LOCALHOSTNAME/s/$/ -Dlog/' < $control >$tmp.control
_save_config $control
$sudo cp $tmp.control $control
_writable_primary_logger
if ! _service pmlogger start 2>&1; then _exit 1; fi | _filter_pcp_start
_wait_for_pmlogger || _exit 1
_check_pmlogger_lock

# real QA test starts here

# pmlc port may be busy, so be prepared to try a few times
#
for i in 1 2 3
do
    pmlc -ie <<End-of-File >$tmp.out 2>&1
connect primary
query sample.event
log mandatory on once sample.event.records
# units are milliseconds
sleep 200
query sample.event
End-of-File
    if grep 'Address already in use' <$tmp.out >>$seq_full
    then
	echo "iter $i: pmlc port busy" >>$seq_full
	sleep 2
    else
	break
    fi
done

_filter <$tmp.out

# success, all done
status=0
exit
